package com.nd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.nd.entity.Cart;
import com.nd.entity.OrderDetail;
import com.nd.entity.Orders;
import com.nd.mapper.CartMapper;
import com.nd.mapper.OrderDetailMapper;
import com.nd.mapper.OrdersMapper;
import com.nd.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yqx
 * @since 2024-12-25
 */
@Service
public class OrdersServiceImpl extends MPJBaseServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired(required = false)
    OrdersMapper ordersMapper;

    @Autowired(required = false)
    OrderDetailMapper orderDetailMapper;

    @Autowired(required = false)
    CartMapper cartMapper;


    @Override
    public boolean addOrder(Orders orders) {
        //1.订单表中插入1条数据：
        //查询购物车清单,计算金额，执行插入
        List<Cart> cartList = cartMapper.getListByDeskId(orders.getDeskId());
        double t = 0;
        for(Cart c : cartList){
            t+= c.getPrice()*c.getNum();
        }
        orders.setTotal(t); //设置计算的总金额
        int num = ordersMapper.insert(orders); //执行插入,自增的id可以直接拿到

        //2.向明细表中，批量插入
        OrderDetail od = new OrderDetail();
        od.setOrderId(orders.getId());
        for(Cart c : cartList){
            od.setProName(c.getPname());
            od.setProPrice(c.getPrice());
            od.setNum(c.getNum());
            od.setProImg(c.getImg());
            orderDetailMapper.insert(od);
        }

        //3.购物车表： 此桌的购物车清空
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",orders.getDeskId());
        int delete = cartMapper.delete(queryWrapper);


        if(num>0){
            return true;
        }
        return false;
    }
}